/**
 * 登录初始化；
 */
var iniLogin = function () {
    $('.js-modal-login,.js-register-box,.js-pwd-box,.wx-box').addClass('hide');
    $('.js-login-box,.js-phone-box').removeClass('hide');
};

/**
 * 获取验证码
 */
var getCaptcha = function (nickname, mobile, callback) {
    $.ajax({
        type: 'post',
        dataType: 'json',
        url: '/user/registerCaptcha',
        data: {
            'country': '+86',
            'operatorName': nickname,
            'operatorMobile': mobile
        },
        async: true,
        beforeSend: function (XMLHttpRequest) {
        },
        success: function (data) {
            callback(data);
        }
    });
};

/**
 * 关闭登录注册页面
 */
$(document).on('click', '.js-modal-login', function () {
    var t = $(this);
    iniLogin();
});

/**
 * 阻止登录注册页面冒泡
 */
$(document).on('click', '.js-login-box,.js-register-box', function (event) {
    event.stopPropagation();
});

/**
 * 登录
 */
$(document).on('click', '.js-login', function () {
    var t = $(this),
        modal_login = $('.js-modal-login');
    modal_login.toggleClass('hide');
});

/**
 * 切换注册
 */
$(document).on('click', '.js-tag-register', function () {
    var t = $(this),
        login_box = $('.js-login-box'),
        register_box = $('.js-register-box');
    login_box.addClass('hide');
    register_box.removeClass('hide');
});

/**
 * 帐号登录
 */
$(document).on('click', '.js-confirm-login', function () {
    var t = $(this),
        url = '/user/loginMobile',
        dataPost = {
            'country': '+86',
            'mobile': $('#js-mobile').val(),
            'password': $('#js-password').val()
        };
    if (!t.hasClass('disabled')) {
        $.ajax({
            type: 'post',
            dataType: 'json',
            url: url,
            data: dataPost,
            async: true,
            beforeSend: function (XMLHttpRequest) {
            },
            success: function (data) {
                if (data.code == 1) {
                    window.location.reload();
                } else {
                    alert(data.message);
                }
            },
            error: function (e) {
                alert(e);
            }
        });
    }
});

/**
 * 注册
 */
$(document).on('click', '.js-register', function () {
    var t = $(this),
        modal_login = $('.js-modal-login'),
        login_box = $('.js-login-box'),
        register_box = $('.js-register-box');
    login_box.addClass('hide');
    register_box.removeClass('hide');
    modal_login.toggleClass('hide');
});


/**
 * 注册下一步
 */
$(document).on('click', '.js-register-next', function () {
    var t = $(this),
        phone_box = $('.js-phone-box'),
        pwd_box = $('.js-pwd-box'),
        nickname = $('#js-register-nickname').val(),
        mobile = $('#js-register-mobile').val();

    if ($.trim(nickname) == '') {
        alert('昵称不能为空');
        return false;
    }

    if ($.trim(mobile) == '') {
        alert('手机号不能为空');
        return false;
    }
    //回调函数
    var callback = function (res) {
        // phone_box.addClass('hide');
        // pwd_box.removeClass('hide');
        if (res.code == 1) {
            alert('短信发送成功，请注意查收');
            phone_box.addClass('hide');
            pwd_box.removeClass('hide');
        } else {
            alert(res.message);
        }
    };

    getCaptcha(nickname, mobile, callback)
});

/**
 * 确认注册
 */
$(document).on('click', '.js-confirm-register', function () {
    var t = $(this),
        url = '/user/registerMobile',
        dataPost = {
            'country': '+86',
            'operatorName': $('#js-register-nickname').val(),
            'operatorMobile': $('#js-register-mobile').val(),
            'operatorPwd': $('#js-register-password').val(),
            'captcha': $('#js-register-captcha').val()
        };
    if (!t.hasClass('disabled')) {
        $.ajax({
            type: 'post',
            dataType: 'json',
            url: url,
            data: dataPost,
            async: true,
            beforeSend: function (XMLHttpRequest) {
            },
            success: function (res) {
                if (res.code == 1) {
                    alert("注册成功:)");
                    window.location.reload();
                } else {
                    alert(res.message);
                }
            },
            error: function (e) {
                alert(e);
            }
        });
    }
});


/**
 * 退出登录
 */
$(document).on('click', '.js-log-out', function () {
    /*$.cookie('totem_auth', '', { path: '/',domain: '.mjimg.com',expires: -1 });
    $.cookie('totem_auth_key', '', { path: '/',domain: '.mjimg.com',expires: -1 });*/
    $.post("/user/loginOut", {}, function (res) {
        if(res.code == 1){
            window.location.reload();
        }
    });
});


$(document).on('click','.js-wx-login',function () {
    var t = $(this),
        wx_box = $('.wx-box'),
        login_box = $('.js-login-box');
    wx_box.removeClass('hide');
    login_box.addClass('hide');

    var obj = new WxLogin({
        id: "login_container",
        appid: "wx60a24a39f726c8b3",
        scope: "snsapi_login",
        redirect_uri: "https%3a%2f%2ft-yunshu.mjimg.com%2fuser%2fwxcallback",
        state: "pc_login",
        style: "",
        href: ""
    });
});

$(document).on('click','.js-qq-login',function () {
    //以下为按钮点击事件的逻辑。注意这里要重新打开窗口
    //否则后面跳转到QQ登录，授权页面时会直接缩小当前浏览器的窗口，而不是打开新窗口
    window.location.href = '/user/qlogin?menubar=1&scrollbars=1&resizable=1&status=1&titlebar=0&location=1';
    // var A=window.open("/user/qlogin","TencentLogin", "width=450,height=320,menubar=0,scrollbars=1,resizable=1,status=1,titlebar=0,toolbar=0,location=1");
});
/**
 * 分页方法
 * @param total_page
 * @param current_page
 * @returns {string}
 */
function generatePagination(total_page,current_page) {

    var stepLength = 4 ,//最多显示5个；
        middle = '', //中间部分
        omit = '<li class="omit">...</li>',
        html = '';
    var n = 0,total = total_page;
    var t_p = parseInt(total_page/stepLength),
        c_p = parseInt(current_page/stepLength);
    if(c_p < t_p){
        total = current_page < stepLength ? stepLength + 1  : (c_p + 1) *stepLength;
        n = current_page < stepLength ? 0 : (c_p)*stepLength - 1;
    }else{
        omit = '';
        total = total_page;
        n = total_page > stepLength ? total_page - stepLength : 0;
    }
    for (var i = n ; i < total; i++) {
        var num = i+ 1,
            is_active = current_page == num ? 'active' : '';
        middle += '<li class="'+ is_active +'" data-page="'+ num +'">'+ num +'</li>'
    }

    html = '<li data-page="1"><i class="icon i-arrow-left"></i></li>'
        + middle
        + omit
        + '<li data-page="' + total_page + '" aria-label="Next"><i class="icon i-arrow-right"></i></li>'
    return html;
};

if($('#pagination').length > 0){
    var t = $('#pagination'),
        total_page = parseInt(t.attr('data-total')),
        current_page = parseInt(t.attr('data-current')),
        html = generatePagination(total_page,current_page);
    if(total_page == '1'){
        t.hide();
    }else{
        t.empty().append(html);
    }

}

Date.prototype.format = function(format) {
    var date = {
        "M+": this.getMonth() + 1,
        "d+": this.getDate(),
        "h+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
        "q+": Math.floor((this.getMonth() + 3) / 3),
        "S+": this.getMilliseconds()
    };
    if (/(y+)/i.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    for (var k in date) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1
                ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
        }
    }
    return format;
};

// console.log(newDate.format('yyyy-MM-dd h:m:s'));

/**
 * 修改密码
 */
$(document).on('click','.js-update-pwd',function () {
    var t = $(this),
        url = '/user/updateUserPwd',
        dataPost = {
            'country': '+86',
            'pwd': $('#pwd').val(),
            'new_pwd': $('#new_pwd').val(),
        };
    if (!t.hasClass('disabled')) {
        $.ajax({
            type: 'post',
            dataType: 'json',
            url: url,
            data: dataPost,
            async: true,
            beforeSend: function (XMLHttpRequest) {
            },
            success: function (data) {
                if (!!data.success) {
                    alert(data.data.msg);
                    location.reload();
                } else {
                    alert(data.data.msg);
                }
            },
            error: function (e) {
                alert(e);
            }
        });
    }
});

/**
 * 修改头像
 */
$(document).on('change','#story-img',function () {
    var t = $(this),
        id = t.attr('id'),
        callBack = function (data) {
            if (!!data.success) {
                t.parents('.member-box').find('img').attr('src',data.data.url);

                var url = '/user/updateUserInfo',
                    dataPost = {
                        'avatar':data.data.url
                    };

                $.ajax({
                    type: 'post',
                    dataType: 'json',
                    url: url,
                    data: dataPost,
                    async: true,
                    beforeSend: function (XMLHttpRequest) {
                    },
                    success: function (data2) {
                        if (!!data2.success) {
                            location.reload();
                        } else {
                            alert(data2.data.msg);
                        }
                    },
                    error: function (e) {
                        alert(e);
                    }
                });

            } else {
                alert(data.data.msg);
            }
        };
    UploadFile('/tool/imageUploadFromAvatar', id, callBack)
});


